<template>
  <div class="case-detail-container">


    <!-- 案件基本信息 -->
    <a-page-header class="demo-page-header" style="border: 1px solid rgb(235, 237, 240); margin-bottom: 24px;"
      title="案件详情" :sub-title="`案件编号：${caseId}`" @back="() => $router.go(-1)">
      <a-spin v-if="caseData.loading" tip="加载中..." size="small" />
      <template #extra>
        <a-button type="primary" key="3" @click="handleRefresh" :loading="caseData.loading">
          <span>刷新</span>
        </a-button>
      </template>
      <!-- 案件基本信息 -->
      <a-descriptions :column="3" :bordered="false">
        <a-descriptions-item label="案件ID">{{ caseData.id }}</a-descriptions-item>
        <a-descriptions-item label="批次名称">{{ caseData.batchName }}</a-descriptions-item>
        <a-descriptions-item label="审核结果">
          <a-tag :color="getStatusColor(caseData.state?.code || '')">
            {{ caseData.state?.message }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="委案商">{{ caseData.entrustBName }}</a-descriptions-item>
        <a-descriptions-item label="审核摘要">
          {{ caseData.auditResult || '暂无摘要' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-page-header>


    <!-- 流程步骤显示 -->

    <a-card type="inner" :body-style="{ padding: '50px 0px 0px' }" style="margin-bottom: 24px; box-shadow: none;">
      <div class="w-[90%] mx-auto justify-between">
        <div class="process-steps mb-5">
          <a-steps :current="processState.currentStep - 1" progress-dot size="small">
            <a-step v-for="step in processSteps" :key="step.key" :title="step.title" />
          </a-steps>
        </div>
        <a-card :bordered="false" type="inner" :body-style="{ padding: '0px' }"
          style="margin-bottom: 24px; box-shadow: none;">

          <!-- 预审阶段 -->
          <div class="case-process" v-if="processState.currentStep === 1">
            <PreAuditStep v-if="caseData.batchName" @file-selected="handleFileSelected" />
          </div>

          <!-- 终审阶段 -->
          <div class="case-process" v-if="processState.currentStep === 2">
            <FinalAuditStep :case-data="caseData" @download-file="downloadFile"
              @update-audit-form="handleAuditFormUpdate" ref="finalAuditStepRef" />

            <!-- 状态提示信息 -->
            <div v-if="caseData.state?.code !== 'PRE_AUDIT_SUCCESS'" class="status-warning">
              <a-alert message="案件状态不符合终审条件" :description="`当前状态：${caseData.state?.message || '未知'}，需要状态为：预审通过`"
                type="warning" show-icon style="margin-top: 16px;" />
            </div>
          </div>
        </a-card>
      </div>
      <template #actions>
        <a-button type="primary" @click="handleNextStep" :loading="processState.isProcessing"
            :disabled="isButtonDisabled()">
            {{ getNextStepButtonText() }}
          </a-button>
      </template>
    </a-card>






    <!-- 案件详情弹框 -->
    <a-modal v-model:open="caseDetailModalVisible" title="案件详情" width="800px" :footer="null">
      <div v-if="caseDetailData">
        <a-descriptions title="案件详情" :column="2" bordered>
          <a-descriptions-item label="案件ID">{{ caseDetailData.id }}</a-descriptions-item>
          <a-descriptions-item label="批次名称">{{ caseDetailData.batchName }}</a-descriptions-item>
          <a-descriptions-item label="委案商">{{ caseDetailData.entrustBName }}</a-descriptions-item>
          <a-descriptions-item label="状态">{{ caseDetailData.state?.message }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>


  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  getReviewDetail,
  getOSSSignature,
  saveAttachment,
  getUploadRecordEntrustInfo,
  auditUploadRecordEntrust,
  finalAuditUploadRecordEntrust,
  getUploadCaseDetail,
} from '../server/api';
import { OssUpload } from '../utils/uploadOss';
import type { GetReviewDetailResult } from '../server/type';
import PreAuditStep from '../components/steps/PreAuditStep.vue';
import FinalAuditStep from '../components/steps/FinalAuditStep.vue';
import { useScheduledTask } from '../composables/useScheduledTask';
import { useExcelStore } from '../store/excel';

const router = useRouter();
const route = useRoute();
const caseId = route.params.id as string;

// 定时任务功能
const { executeTask: executeScheduledTask } = useScheduledTask();

// Excel store
const excelStore = useExcelStore();


// 流程状态
const processState = reactive({
  currentStep: 1, // 1: 预审, 2: 终审, 3: 完成
  isProcessing: false,
  customerInfo: [] as any[], // 客户信息缓存
  loanIds: [] as string[], // loanIds缓存
  hasSelectedFile: false // 是否已选择文件
});

// 流程步骤配置
const processSteps = [
  { key: 1, title: '预审', description: '上传Excel文档完成案件预审' },
  { key: 2, title: '终审', description: '对预审通过的案件进行终审' },
  { key: 3, title: '完成', description: '案件审核流程已完成' }
];

/**
 * 根据案件状态动态设置当前步骤
 * @param stateCode 案件状态码
 */
const setCurrentStepByState = (stateCode: string) => {
  switch (stateCode) {
    case 'TO_AUDIT':
    case 'PRE_AUDIT_FAILED':
      processState.currentStep = 1; // 预审
      break;
    case 'AUDITING':
    case 'PRE_AUDIT_SUCCESS':
    case 'AUDIT_FAILED':
      processState.currentStep = 2; // 终审
      break;
    case 'AUDIT_SUCCESS':
      processState.currentStep = 3; // 完成
      break;
    default:
      processState.currentStep = 1; // 默认预审
      break;
  }
};


// 案件数据
const caseData = reactive<GetReviewDetailResult & {
  loading: boolean;
  error: string | null;
  batchId?: string;
  auditFile?: string;
  auditResult?: string;
  auditSummary?: string;
  finalAuditResult?: string;
  customerList?: any[];
  entrustList?: any[];
  hasEntrusted?: boolean;
}>({
  loading: false,
  error: null,
  id: caseId,
  batchName: '',
  entrustBName: '',
  state: {
    code: '',
    message: ''
  },
  batchId: '',
  auditFile: '',
  auditResult: '',
  auditSummary: '',
  finalAuditResult: '',
  customerList: [],
  entrustList: [],
  hasEntrusted: false
});

// 审核表单
const reviewForm = reactive({
  id: caseId,
  state: 'AUDIT_SUCCESS'
});

// 弹框状态
const caseDetailModalVisible = ref(false);

// 案件详情数据
const caseDetailData = ref<any>(null);


// 组件引用
const finalAuditStepRef = ref();

// 选中的客户ID列表



// 文件上传状态
const uploadState = reactive({
  loading: false,
  error: null as string | null
});

// 获取签名参数
const getOSSSignatureParams = reactive({
  accessType: 'AUDIT_CASE_FILE',
  fileName: '',
  objectId: caseId,
  protocol: 'https'
});

// 上传OSS参数
const uploadFileToOSSParams = reactive({
  fileType: '',
  url: '',
  objectId: caseId,
  fileName: '',
  uploadType: 'AUDIT_CASE_FILE',
  bizType: 'AUDIT_CASE_FILE',
  protocol: 'https',
});



/**
 * 获取OSS签名
 * @param params 签名参数
 * @returns 签名信息
 */
const getSignature = async (params: any) => {
  try {
    const signature = await getOSSSignature(params);
    if (!signature) {
      throw new Error('获取签名失败');
    }
    return signature;
  } catch (error) {
    console.error('获取OSS签名失败:', error);
    throw new Error('获取文件上传签名失败，请重试');
  }
};

/**
 * 上传文件到OSS
 * @param params 上传参数
 */
const uploadFileToOSS = async (params: any) => {
  try {
    const data = await saveAttachment(params);
    if (!data) {
      throw new Error('上传失败');
    }
    return data;
  } catch (error) {
    console.error('文件上传到OSS失败:', error);
    throw new Error('文件上传失败，请重试');
  }
};



/**
 * 处理文件选择回调
 * @param file 选择的文件对象
 */
const handleFileSelected = async (file: File) => {
  // 文件基本信息（保留关键信息用于调试）
  console.log('文件上传开始:', { name: file.name, size: file.size, type: file.type });

  // 标记已选择文件
  processState.hasSelectedFile = true;

  uploadState.loading = true;
  uploadState.error = null;

  try {
    // 文件大小验证（限制为50MB）
    const maxSize = 50 * 1024 * 1024; // 50MB
    if (file.size > maxSize) {
      throw new Error('文件大小不能超过50MB');
    }

    // 文件类型验证
    const allowedTypes = [
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];
    if (!allowedTypes.includes(file.type)) {
      throw new Error('只支持Excel文件格式(.xlsx, .xls)');
    }

    message.loading('正在处理文件...', 0);

    // 设置OSS签名参数
    getOSSSignatureParams.fileName = file.name;

    // 获取OSS签名
    const signature = await getSignature(getOSSSignatureParams);

    console.log('signature', signature);
    // 设置上传文件到OSS参数
    uploadFileToOSSParams.fileName = file.name;
    uploadFileToOSSParams.fileType = file.type;

    if (signature.success) {
      uploadFileToOSSParams.url = signature.result.dir;
      // 上传文件到OSS
      await OssUpload(signature.result, file);
    }

    // 保存上传文件的信息到系统
    await uploadFileToOSS(uploadFileToOSSParams);

    // 获取客户信息
    const customerInfo = await getUploadCaseDetail({
      uploadRecordId: caseId,
      clientName: '',
      state: 'INIT',
      current: 1,
      size: 500,
    });
    if (customerInfo.success && customerInfo.result) {
      const uploadCaseUserList = customerInfo.result.records;
      // 保存客户信息到状态
      processState.customerInfo = uploadCaseUserList;
    }


    message.destroy();
    message.success(`文件 "${file.name}" 上传成功，客户信息已获取`);

  } catch (error) {
    message.destroy();
    const errorMessage = error instanceof Error ? error.message : '文件处理失败';
    message.error(errorMessage);
    uploadState.error = errorMessage;

    // 重置文件选择状态
    processState.hasSelectedFile = false;

    // 记录错误信息用于调试
    console.error('文件处理失败:', error);
  } finally {
    uploadState.loading = false;
  }
};

/**
 * 获取案件详情
 */
const fetchCaseDetail = async () => {
  caseData.loading = true;
  caseData.error = null;

  try {
    if (!caseId) {
      throw new Error('案件ID不能为空');
    }

    // 使用新的API获取案件基本信息
    const result = await getUploadRecordEntrustInfo({ id: caseId });
    if (result.success && result.result) {
      Object.assign(caseData, result.result);
      // 根据案件状态动态设置当前步骤
      setCurrentStepByState(caseData.state?.code || '');
    } else {
      // 如果新API失败，回退到旧API
      const data = await getReviewDetail(caseId);
      if (!data) {
        throw new Error('获取案件详情失败');
      }
      Object.assign(caseData, data);
      // 根据案件状态动态设置当前步骤
      setCurrentStepByState(caseData.state?.code || '');
    }

  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '网络错误，请稍后重试';
    caseData.error = errorMessage;
    message.error(errorMessage);

    // 记录错误信息用于调试
    console.error('获取案件详情失败:', error);
  } finally {
    caseData.loading = false;
  }
};




// 组件挂载时获取数据
onMounted(async () => {
  // 清空之前的Excel文件状态
  clearExcelCache();
  await fetchCaseDetail();
  loadCustomerInfoFromCache();
});

/**
 * 清空Excel文件状态
 */
const clearExcelCache = () => {
  try {
    // 清空流程状态中的文件选择状态
    processState.hasSelectedFile = false;
    processState.customerInfo = [];
    // 清空Excel store中的状态
    excelStore.clearAll();
    console.log('已清空Excel文件状态和Excel store状态');
  } catch (error) {
    console.error('清空Excel文件状态失败:', error);
  }
};

/**
 * 从缓存加载客户信息
 * 注意：已移除localStorage相关代码，此函数保留用于未来扩展
 */
const loadCustomerInfoFromCache = () => {
  // 客户信息现在直接从API获取，不再从localStorage加载
  console.log('客户信息直接从API获取，无需从缓存加载');
};

onUnmounted(() => {

});

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'AUDITING': 'blue',
    'TO_AUDIT': 'orange',
    'AUDIT_SUCCESS': 'success',
    'PRE_AUDIT_FAILED': 'danger',
    'PRE_AUDIT_SUCCESS': 'success',
    'AUDIT_FAIL': 'error',
    'ASSIGNED': 'orange',
    'OUTSOURCED': 'purple'
  };
  return colorMap[status] || 'default';
};

// 判断按钮是否应该禁用
const isButtonDisabled = () => {
  // 预审步骤：没有选择文件时禁用
  if (processState.currentStep === 1) {
    return !processState.hasSelectedFile;
  }

  // 终审步骤：状态不是PRE_AUDIT_SUCCESS时禁用
  if (processState.currentStep === 2) {
    return caseData.state?.code !== 'PRE_AUDIT_SUCCESS';
  }

  // 其他步骤不禁用
  return false;
};


/**
 * 刷新案件详情
 */
const handleRefresh = async () => {
  await fetchCaseDetail();
};

/**
 * 下一步处理
 */
const handleNextStep = async () => {
  try {
    processState.isProcessing = true;

    if (processState.currentStep === 1) {
      // 预审阶段
      await handlePreAudit();
    } else if (processState.currentStep === 2) {
      // 终审阶段
      await handleFinalAudit();
    } else if (processState.currentStep === 3) {
      // 完成阶段 - 执行定时任务
      await handleProcessComplete();
    }

  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '提交失败，请重试';
    message.error(errorMessage);
    console.error('提交失败:', error);
  } finally {
    processState.isProcessing = false;
  }
};

/**
 * 处理流程完成
 */
const handleProcessComplete = async () => {
  try {
    console.log('开始执行流程完成定时任务...');

    // 执行定时任务
    const taskSuccess = await executeScheduledTask();

    if (taskSuccess) {
      message.success('案件审核流程已完成，定时任务执行成功，1.5秒后跳转到委案页面');
      console.log('定时任务执行成功');
    } else {
      message.warning('案件审核流程已完成，但定时任务执行失败，1.5秒后跳转到委案页面');
      console.warn('定时任务执行失败');
    }

    // 刷新案件详情
    await fetchCaseDetail();

    // 延迟1.5秒后跳转到委案页面
    setTimeout(() => {
      console.log('跳转到委案页面...');
      router.push('/entrust-list');
    }, 500);

  } catch (error) {
    console.error('流程完成处理失败:', error);
    message.error('流程完成处理失败，请重试');
  }
};

/**
 * 跳过定时任务
 */


/**
 * 处理预审
 */
const handlePreAudit = async () => {
  const hideLoading = message.loading('正在提交预审信息...', 0);

  try {
    // 调用新的预审接口
    const params = {
      id: caseId,
      state: reviewForm.state
    };

    const res = await auditUploadRecordEntrust(params);
    console.log('预审结果:', res);

    hideLoading();
    message.success('预审提交成功');

    // 重新获取案件详情，更新状态
    await fetchCaseDetail();

  } catch (error) {
    hideLoading();
    throw error;
  }
};

/**
 * 处理终审
 */
const handleFinalAudit = async () => {
  const hideLoading = message.loading('正在提交终审信息...', 0);

  try {
    // 调用新的终审接口
    const params = {
      id: caseId,
      state: reviewForm.state
    };

    const res = await finalAuditUploadRecordEntrust(params);
    console.log('终审结果:', res);

    hideLoading();
    message.success('终审提交成功');

    // 重新获取案件详情，更新状态
    await fetchCaseDetail();

  } catch (error) {
    hideLoading();
    throw error;
  }
};

/**
 * 处理委案
 */




/**
 * 获取下一步按钮文本
 */
const getNextStepButtonText = (): string => {
  switch (processState.currentStep) {
    case 1:
      return '提交预审';
    case 2:
      return '提交终审';
    case 3:
      return '流程完成';
    default:
      return '下一步';
  }
};



// 处理审核表单更新
const handleAuditFormUpdate = (auditForm: any) => {
  reviewForm.state = auditForm.state;
};

// 全选分案客户


/**
 * 下载文件
 */
const downloadFile = (url: string) => {
  if (url) {
    window.open(url, '_blank');
  } else {
    message.warning('文件链接不存在');
  }
};


/**
 * 下载摘要
 */



</script>

<style scoped>
.case-detail-container {
  position: relative;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);


}

:deep(.ant-card) {
  box-shadow: none;
  border-radius: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.case-info,
.case-amount,
.case-process {
  margin-bottom: 24px;
}

.case-info h3,
.case-amount h3,
.case-process h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.case-basic {
  display: flex;
  align-items: center;
}

.case-basic h3 {
  margin: 0 16px 0 0;
}

.info-content {
  padding-top: 16px;
}

.info-row {
  display: flex;
  margin-bottom: 16px;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.info-item span {
  color: #1a1a1a;
}

.amount-content {
  padding-top: 16px;
}

.amount-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.amount-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.amount-item label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.amount-value {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.amount-unit {
  font-size: 14px;
  color: #666;
  margin-left: 4px;
}

/* Excel组件相关样式 */
.excel-section {
  margin-bottom: 24px;
}

/* 章节标题样式 */
.section-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #1a1a1a;
}

/* 流程步骤样式 */
.process-steps {
  margin-bottom: 30px;
}

.process-steps .ant-steps {
  margin-top: 16px;
}

/* 委案信息样式 */
.entrust-info {
  margin-top: 16px;
}

.entrust-info .ant-descriptions {
  margin-top: 16px;
}

/* 定时任务信息样式 */
.scheduled-task-info {
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
  margin-top: 16px;
}

.scheduled-task-info p {
  margin: 0 0 8px 0;
  color: #666;
}

.scheduled-task-info p:last-child {
  margin-bottom: 0;
}

/* 步骤操作按钮样式 */
.step-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

/* a-affix 居中样式 */
.affix-container {
  position: absolute;
  bottom: 100px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 16px;
  z-index: 2000;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .info-row {
    flex-direction: column;
    gap: 12px;
  }

  .process-steps .ant-steps {
    flex-direction: column;
  }
}
</style>